﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using Oracle.DataAccess.Client;

namespace SO_DataFetcher.PubFunctions.DataBaseHelp
{
    public class OracleHelp:DataBaseHelper
    {
        private static OracleHelp _instance;

        public override void Instance()
        {
            _instance = new OracleHelp();
        }

        private OracleConnection _oracleConnection;
        private OracleConnection OracleConnection
        {
            get { return _oracleConnection ?? (_oracleConnection = new OracleConnection(_instance.Connecting)); }
        }

        public override void GetConnectString(string ip, string port, string name, string psw, string dataTable)
        {
            _instance.Connecting = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + ip + ")(PORT=" + port + "))" +
                          "(CONNECT_DATA=(SID=" + dataTable + ")));User Id="+name+";Password="+psw+";";
        }
   
        public override  void ExecuteSql(string sql)
        {
            OracleCommand cmd = new OracleCommand(sql, _instance.OracleConnection);
            try
            {
                OpenConnection();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
               CloseConnection();
            }
        }

        public override DataSet GetDataSet(string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                OpenConnection();

                OracleDataAdapter adapter = new OracleDataAdapter(sql, _instance.OracleConnection);
                adapter.Fill(ds);
            }
            catch(Exception ex)
            {
            }
            finally
            {
                CloseConnection();
            }

            return ds;
        }

        public override void OpenConnection()
        {
            if (_instance.OracleConnection.State == ConnectionState.Closed)
                _instance.OracleConnection.Open();
        }

        public override void CloseConnection()
        {
            if (_instance.OracleConnection.State == ConnectionState.Open)
                _instance.OracleConnection.Close();
        }
    }
}
